<template>
  <div class="action-process action-group" :class="{'action-process-plain':actionModel.param && actionModel.param.fields && isPlain}">
    <template v-if="actionModel.param && actionModel.param.select_rangeset">
      <Selector class="select-box" :path="fetchPath" @selectChange="selectChange" :placeholder="selectPlaceholder"></Selector>
      <Button type="info" :icon="actionModel.icon || 'share'" :loading="loading" @click="actionTrigger">{{actionModel.name}}</Button>
    </template>
    <template v-else-if="actionModel.param &&  actionModel.param.select_data">
      <RadioGroup class="radio-box" :data="radioData" v-model="stateData"></RadioGroup>
      <Button type="info" :icon="actionModel.icon || 'share'" :loading="loading" @click="actionTrigger">{{actionModel.name}}</Button>
    </template>
    <template v-else-if="actionModel.param && actionModel.param.fields && isPlain">
      <TableForm ref="actionform" class="search-form form-process-plain" :stateAll="false" :enableColCount="false" size="small" :model="actionModels" :hasLabel="actionModels.fields.length>=2" @validate="validateChange" :col="formCol"></TableForm>
      <Button type="info" :icon="actionModel.icon || 'share'" :loading="loading" @click="actionTrigger">{{actionModel.name}}</Button>
    </template>
    <template v-else-if="actionModel.param && actionModel.param.fields && isCollapse">
      <div>
        <layer v-model="showForm" :placeX="actionModel.locate || 'left'" v-clickOut="hideForm" :zIndex="999" :shadow="true">
        <Button slot="button" type="info" :icon="actionModel.icon || 'share'" @click="showForm = !showForm" class="main-btn" :loading="loading" >
          {{actionModel.name}}
          <i class="ivu-icon ivu-icon-arrow-down-b" v-show="!showForm"></i>
          <i class="ivu-icon ivu-icon-arrow-up-b" v-show="showForm"></i>
        </Button>
        <div slot="body"  class="action-wrap">
            <TableForm ref="actionform" :col="actionModel.param.fields.length<2?1:2" :stateAll="false" :enableColCount="false" size="small" :model="actionModels" @validate="validateChange"></TableForm>
            <div class="btn-list">
              <Button @click="showForm = false" class="cancle-button">取消</Button>
              <Button type="primary" :loading="loading" @click="formSubmit">确定</Button>
            </div>
        </div>
       </layer>
      </div>
    </template>
    <template v-else-if="actionModel.param && actionModel.param.fields && isModal">
      <Button type="info" v-show="isShow" :icon="actionModel.icon || 'share'" @click.stop="openModal">
        {{actionModel.name}}
        <i class="ivu-icon ivu-icon-arrow-down-b" v-show="!modal"></i>
        <i class="ivu-icon ivu-icon-arrow-up-b" v-show="modal"></i>
      </Button>
      <Modal v-model="modal" :closable="false" :title="actionModel.name">
        <TableForm ref="actionform" :col="actionModel.param.fields.length<2?1:2" :stateAll="false" :enableColCount="false" size="small" :model="actionModels" @validate="validateChange"></TableForm>
        <div slot="footer">
          <Button @click="modal = false" class="cancle-button">取消</Button>
          <Button type="primary" :loading="loading" @click="submitModal">确定</Button>
        </div>
      </Modal>
    </template>
    <Button v-else class="action-button action" :loading="loading" :disabled="!actionEnable" v-show="buttonShow" :icon="actionModel.icon" :type="buttonType" @click="actionTrigger">
      {{actionModel.name}}
    </Button>
  </div>
</template>
<script>
import layer from "@/element/layer"
import base from "../actionBase";
import ActionForm from "@/components/form";
import TableForm from "@/components/formTable";
import $ from "@/common";
import clickOut from "@/directives/click-out";
import Selector from "@/components/selector";
import RadioGroup from "@/element/radioGroup";
export default {
  extends: base,
  directives: { clickOut },
  data() {
    return {
      modalId: "",
      modalData: {},
      showForm: false,
      selectData: null,
      stateData: null,
      submitMethod: "POST",
      updateOwner: true,
      enableSubmit: true,
      modal: false,
      formCol: 2
    };
  },
  computed: {
    isPlain() {
      if (this.actionModel.locate === "inline") {
        return false;
      }
      if (this.actionModel.param.form_display === "plain") {
        return true;
      } else {
        return false;
      }
    },
    isCollapse() {
      if (this.actionModel.locate === "inline") {
        return false;
      }
      if (this.actionModel.param.form_display === "collapse") {
        return true;
      }
      if (
        this.actionModel.param.form_display === undefined ||
        this.actionModel.param.form_display === "auto"
      ) {
        if (this.actionModel.param.fields) {
          if (this.actionModel.param.fields.length) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isModal() {
      if (this.actionModel.locate === "inline") {
        return true;
      }
      if (this.actionModel.param.form_display === "modal") {
        return true;
      }
    },
    isShow() {
      if (this.actionModel.locate === "inline") {
        return false;
      } else {
        return true;
      }
    },
    actionModels() {
      return {
        code: this.actionModel.code,
        fields: this.actionModel.param.fields
      };
    },
    selectPlaceholder() {
      return (
        "请选择" +
        ((this.actionModel.param && this.actionModel.param.select_name) || "")
      );
    },
    radioData() {
      var rangeset = this.actionModel.param.select_data;
      var stateMap = {};
      if (rangeset) {
        if (typeof rangeset === "string") {
          let list;
          if (rangeset.indexOf("@") < 0 && rangeset.indexOf(";") >= 0) {
            list = rangeset.split(";");
          } else {
            list = rangeset.split("@");
          }
          list.forEach(str => {
            let item = str.split(":");
            if (this.stateData === null) {
              this.stateData = item[0];
            }
            stateMap[item[0]] = item[1];
          });
        } else if (typeof rangeset === "object") {
          stateMap = rangeset;
        }
      }
      return stateMap;
    },
    rangeset() {
      var rangeset = this.actionModel.param.select_rangeset || {};
      if (rangeset && typeof rangeset === "string") {
        try {
          rangeset = JSON.parse(rangeset);
        } catch (ex) {
          rangeset = {
            code: rangeset
          };
        }
      }
      return rangeset;
    },
    fetchPath() {
      if (this.rangeset) {
        if (this.rangeset.path) {
          return this.rangeset.path;
        } else if (this.rangeset.dataset || this.rangeset.code) {
          return `/service/{app}/dataset/data/${this.rangeset.dataset ||
            this.rangeset.code}`;
        }
      }
    }
  },
  methods: {
    hideForm(e) {
      if (e.target.classList[0] !== "bk-select-item") {
        this.showForm = false;
      }
    },
    validateChange(v) {
      this.enableSubmit = v;
    },
    openModal(id, data) {
      this.modal = true;
      if (id) {
        this.modalId = id;
        this.modalData = data;
      }
      this.$refs.actionform && this.$refs.actionform.setData({});
    },
    submitModal() {
      this.$refs.actionform && this.$refs.actionform.doValidate();
      this.$nextTick(() => {
        if (!this.enableSubmit) {
          this.$Message.error("表单验证失败!");
        } else {
          if (this.modalId) {
            this.actionStart(this.modalId, this.modalData);
            this.modalId = "";
            this.modalData = "";
          } else {
            this.actionStart();
          }
        }
      });
    },
    formSubmit() {
      this.$refs.actionform.doValidate();
      this.$nextTick(() => {
        if (!this.enableSubmit) {
          this.$Message.error("表单验证失败!");
        } else {
          this.actionTrigger();
        }
      });
    },
    actionTrigger(id, data) {
      if (
        this.actionModel.locate === "inline" &&
        this.actionModel.param &&
        this.actionModel.param.fields
      ) {
        this.openModal(id, data);
      } else {
        if (this.actionModel.param.check_path) {
          $.link(this.actionModel.param.check_path, data).then(res => {
            let result = res.data.result
            if (result) {
              let content = res.data.content
              return new Promise((resolve, reject) => {
                this.$Modal.confirm({
                  title: "确认操作",
                  content: this.confirmText() + content,
                  onOk: () =>
                    this.actionStart(id, data)
                      .then(res => {
                        this.showForm = false;
                        resolve(res);
                      })
                      .catch(res => {
                        reject(res);
                      }),
                  onCancel() {
                    resolve();
                  }
                });
              });
            } else {
              return new Promise((resolve, reject) => {
                this.actionStart(id, data).then(res => {
                    this.showForm = false;
                    resolve(res);
                  }).catch(res => {
                    reject(res);
                  })
              });
            }
          }).catch((error) => {
            console.error(error)
          });
        } else {
          return new Promise((resolve, reject) => {
            this.$Modal.confirm({
              title: "确认操作",
              content: this.confirmText(),
              onOk: () =>
                this.actionStart(id, data)
                  .then(res => {
                    this.showForm = false;
                    resolve(res);
                  })
                  .catch(res => {
                    reject(res);
                  }),
              onCancel() {
                resolve();
              }
            });
          });
        }
      }
    },
    submitPath() {
      return this.model.path;
    },
    confirmText() {
      var text = "确认执行" + this.actionModel.name + "操作";
      if (this.actionModel.scope === "optional") {
        var count = this.$owner.getSelectedIds().length;
        if (count > 0) {
          text =
            "确认对当前选中的" +
            count +
            "条数据执行" +
            this.actionModel.name +
            "操作";
        } else {
          text = `确认对当前过滤的 <span class="red bold">全部</span> 共 <span class="blue bold">${this
            .$owner.totalCount ||
            this.$owner.listData.length}</span> 条数据 执行${
            this.actionModel.name
          }操作`;
        }
      }
      text += '</br>'
      return text;
    },
    actionStart(id, data) {
      /**
       * @Description : 2018-07-26 BUG 修复
       * @ModifiedBy : Note: 对JSON.stringify的重复调用不应该重用缓存。
       * @Param paramData
       */
      this.beforeActionStart(id, data);
      this.loading = true;
      var postData = this.getSubmitData();
      //对于单独传入数据的处理（行内action和跨层调用时的情况）
      if (data !== undefined && data !== null) {
        switch (this.actionModel.scope) {
          case "rows":
            postData = [data.id];
            break;
          case "optional":
            postData = postData || {};
            postData.rows = [data.id || data];
            break;
          default:
            postData = data;
        }
      }
      if (
        this.actionModel.param.select_rangeset &&
        this.selectData !== null &&
        this.selectData !== undefined
      ) {
        postData[this.actionModel.param.select_param_key] = this.selectData[
          this.actionModel.param.select_key
        ];
      }
      if (
        this.actionModel.param.select_data &&
        this.stateData !== null &&
        this.stateData !== undefined
      ) {
        postData[this.actionModel.param.select_param_key] = this.stateData;
      }
      var paramData = data || this.getDataRow();
      //获取上级主表表单编码
      var mainForm = $.getParent(this, "isForm", true);
      if (mainForm) {
        paramData.parent = mainForm.formData;
        for (let i in paramData.parent) {
          paramData[`parent.${i}`] = paramData.parent[i];
        }
      }
      if (this.actionModel.param.fields) {
        if (this.actionModel.param.param_key) {
          postData[
            this.actionModel.param.param_key
          ] = this.$refs.actionform.formData;
        } else {
          postData.param = postData.param || {};
          Object.assign(postData.param, this.$refs.actionform.formData);
        }
      }
      /**
       * @Description : 2018-07-23 BUG 修复
       * @ModifiedBy : 解决系统管理-应用安装POST提交数据 字符串 问题
       * @Param null
       */
      return $.link(this.submitPath(), postData, {
        method: this.submitMethod,
        param: paramData
      }).then(res => {
          this.modal = false;
          this.actionSuccess();
          //所有者更新数据
          if (this.updateOwner) {
            this.$owner.update();
            //数据刷新标记，用于
            this.$owner.updateMark = true;
          }
        }).finally(() => {
          this.loading = false;
        });
    },
    beforeActionStart(id, data) {},
    selectChange(v) {
      this.selectData = v;
    }
  },
  created() {
    if (this.$owner.fackOwner) {
      this.$owner = this.$owner.$owner;
    }
    $.setObj(this.actionModel, {
      param: {
        select_key: "id",
        select_param_key: "id"
      }
    });
  },
  components: {
    Selector,
    RadioGroup,
    ActionForm,
    TableForm,
    layer
  }
};
</script>
<style lang="less">
.action-wrap {
  min-width: 285px;
  padding: 12px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
  .btn-list {
    text-align: right;
    margin-top: 10px;
    .cancle-button {
      margin-right: 6px;
    }
  }
  .field-control {
    margin-bottom: 5px;
  }
}
.action-process-plain {
  display: flex;
  align-items: flex-end;
  > .ivu-btn {
    display: block;
    height: 32px;
  }
  .search-form.form-process-plain {
    flex: 1;
    display: block;
    padding: 0 8px;
    border-top-width: 0;
    margin-bottom: -4px !important;
    .field-control {
      margin-bottom: 0px;
    }
  }
}
.action-wrap-left {
  left: 0;
}

.action-wrap-right {
  right: 0;
}

.main-btn {
  padding-right: 10px;
  .ivu-icon {
    margin-left: 6px;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.6s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
